<template>
  <div class="flex-column">
    <div class="flex justify-between">
      <div class="flex">
        <el-button v-if="permission.addBtn" type="primary" icon="el-icon-plus" @click="add">{{
          $t('ADD')
        }}</el-button>
      </div>
      <div class="flex flex-wrap">
        <el-input
          v-model.trim="param.keyword"
          style="width: 300px"
          maxlength="32"
          clearable
          class="ml-10 mb-10"
          :placeholder="$t('PARTNUMBER') + '/' + $t('CHARACTERNAME')"
          @keyup.enter.native="$debounce(search)"
        />
        <el-button type="primary" class="ml-10 mb-10" @click="$debounce(search)">{{
          $t('QUERY')
        }}</el-button>
      </div>
    </div>
    <el-table :data="list" height="100%" border>
      <template slot="empty">
        <NullData />
      </template>
      <el-table-column :label="$t('PARTNUMBER')" prop="roleId" width="200" align="left" />
      <el-table-column :label="$t('CHARACTERNAME')" prop="roleName" width="200" />
      <el-table-column
        :label="$t('DESCRIPTION')"
        prop="description"
        show-overflow-tooltip
        align="left"
      />
      <el-table-column :label="$t('WHETHER_ENABLE')" prop="enable" width="100" align="left">
        <template v-slot="{ row }">
          {{ row.enable ? $t('ENABLE') : $t('DISABLE') }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('OPERATE')"
        class-name="operate-cell"
        :width="resetSize(200)"
        fixed="right"
      >
        <template v-slot="{ row }">
          <el-button type="text" size="mini" @click="view(row)">{{ $t('VIEW') }}</el-button>
          <el-button v-if="modAuth(row)" type="text" size="mini" @click="mod(row)">{{
            $t('MOD')
          }}</el-button>
          <el-button
            v-if="permission.func && row.roleId != 'admin'"
            type="text"
            size="mini"
            @click="auth(row)"
          >{{ $t('AUTH_TYPE_FUNC') }}</el-button>
          <el-button v-if="delAuth(row)" type="text" size="mini" @click="del(row)">{{
            $t('DEL')
          }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="mt-10 text-right"
      layout="total, sizes, prev, pager, next, jumper"
      background
      :current-page="page.page"
      :page-size="page.size"
      :total="page.total"
      @size-change="sizeChange"
      @current-change="currentChange"
    />
    <edit :visible="editShow" :type="operateType" :data="row" @close="close" />
    <func-auth :visible="authShow" :data="row" @close="authShow = false" />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import RoleApi from '@/api/system/RoleApi'
  import RelateApi from '@/api/system/RelateApi'
  import Edit from './Edit'
  import FuncAuth from './FuncAuth'

  export default {
    name: 'SystemRole',
    components: { Edit, FuncAuth },
    data() {
      return {
        list: [],
        param: {},
        page: {
          page: 1,
          size: 20,
          total: 0
        },
        row: {},
        operateType: 'add',
        editShow: false,
        authShow: false
      }
    },
    computed: {
      ...mapGetters(['getUser', 'getRoles']),
      permission() {
        return this.$store.getters.getAuthData('sys:role')
      }
    },
    created() {
      this.loadData()
    },
    methods: {
      loadData() {
        const param = Object.assign({}, this.page, this.param)
        RoleApi.page(param).then(result => {
          if (result.list) {
            this.list = result.list
          } else {
            this.list = []
          }
          this.page.total = result.total
        })
      },
      search() {
        this.page.page = 1
        this.loadData()
      },
      sizeChange(size) {
        this.page.size = size
        this.loadData()
      },
      currentChange(page) {
        this.page.page = page
        this.loadData()
      },
      view(row) {
        this.operateType = 'view'
        this.row = row
        this.editShow = true
      },
      add() {
        this.operateType = 'add'
        this.row = {}
        this.editShow = true
      },
      mod(row) {
        this.operateType = 'mod'
        this.row = row
        this.editShow = true
      },
      async del(row) {
        const list = await RelateApi.list({ targetId: row.roleId, relateType: 'USER_ROLE' })
        if (list && list.length) {
          this.$message.error(
            this.$t('DEL_ROLE_CONFIRM', {
              name: row.roleName,
              user: list.map(i => i.objectId).join('、')
            })
          )
          return
        }
        this.$confirm(
          this.$t('CONFIRM_DELETION_PROMPT_TIP', { key: this.$t('ROLE'), value: row.roleName }),
          { type: 'warning' }
        )
          .then(() => {
            this.delRole(row)
          })
          .catch(() => {})
      },
      async delRole(row) {
        const result = await RoleApi.del(row.id, { roleId: row.roleId, roleName: row.roleName })
        if (result) {
          this.$message.success(this.$t('DELETE_SUCCESS'))
          this.loadData()
        }
      },
      auth(row) {
        this.row = row
        this.authShow = true
      },
      close(load) {
        this.editShow = false
        if (load === true) {
          this.loadData()
        }
      },
      modAuth(row) {
        let canMod = true
        const currentRole = window.__config__.roleLevel.find(i => i.id === this.getRoles[0]) || ''
        const currentRowRole = window.__config__.roleLevel.find(i => i.id === row.roleId) || ''
        if (currentRowRole) {
          // 特殊情况，admin可以修改所有
          if (currentRole.level <= currentRowRole.level) {
            canMod = true
          } else {
            canMod = false
          }
        }
        return (
          this.permission.del && row.roleId !== this.getRoles[0] && row.roleId !== 'admin' && canMod
        )
      },
      async delAuth(row) {
        let canDel = true
        const currentRole = window.__config__.roleLevel.find(i => i.id === this.getRoles[0]) || ''
        const currentRowRole = window.__config__.roleLevel.find(i => i.id === row.roleId) || ''
        if (currentRowRole) {
          if (currentRole.level < 2) {
            canDel = true
          } else {
            canDel = false
          }
        }
        return (
          this.permission.del && row.roleId !== this.getRoles[0] && row.roleId !== 'admin' && canDel
        )
      }
    }
  }
</script>

<style scoped></style>
